<?php
namespace App\Http\Controllers\Admin;

use App\Service\Admin\ImageService;
use App\Service\Admin\LevelService;
use App\Utilitys\Upload;
use Illuminate\Http\Request;

class LevelController extends BaseController
{
    //会员等级

    public function __construct(LevelService $service)
    {
        $this->db = $service;
    }

    //列表
    public function getIndex(Request $request)
    {
        $res = $this->db->getList();
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data'], $res['total']);
    }

    //一个
    public function getOne(Request $request)
    {
        $id = $request->post('id', 0);
        $res = $this->db->getOne($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson(0, '', $res['data']);
    }

    //修改
    public function modify(Request $request)
    {
        $id = $request->post('id', 0);
        $pas['title'] = $request->post('title', '');
        $pas['ver'] = $request->post('ver', '');
        $pas['describe'] = $request->post('describe', '');
        $pas['icon'] = $request->post('icon', '');
        $pas['price'] = $request->post('price', 0);
        $pas['type'] = $request->post('type', 1);
        $pas['real_cost'] = $request->post('real_cost', 0);
        $pas['discount'] = $request->post('discount', 0);
        $pas['real_cost'] = $pas['real_cost'] ? $pas['real_cost'] : 0;
        if (!$pas['title']) {
            return $this->toJson(-2, '等级名称必须的');
        }
//        if (!$icon) {
//            return $this->toJson(-2, '等级图标必须的');
//        }
//        if (!$price) {
//            return $this->toJson(-2, '等级价位必须的');
//        }
        if ($pas['icon']) {
            $imgs = getimagesize($pas['icon']);
            //$iconpath = Upload::getPathByBase64($icon);
            (new ImageService())->addOne($pas['icon'], $imgs[0], $imgs[1]);
        }
        if ($pas['discount']) {
            $pas['discount'] = strlen($pas['discount'])==1 ? $pas['discount'] . '0' : $pas['discount'];
        }
        if (!$id) {
            $res = $this->db->addOne($pas);
        } else {
            $res = $this->db->modify($id, $pas);
        }
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }

    //删除
    public function setDel(Request $request)
    {
        $id = $request->post('id', 0);
        if (!$id) {
            return $this->toJson(-2, '门店ID必须的');
        }
        $res = $this->db->setDel($id);
        if ($res['code'] < 0) {
            return $this->toJson(-2, $res['msg']);
        }
        return $this->toJson();
    }
}